﻿using Service.Auth.Infrastructure.Utils;
using Service.Framework;
using Service.Repository;
using SqlSugar;

namespace Service.Auth.Domain;

public class PasswordValueObject : ValueObject
{
    private const int MinPasswordLength = 6;
    private static readonly Func<char, bool> IsLower = c => c >= 'a' && c <= 'z';
    private static readonly Func<char, bool> IsUpper = c => c >= 'A' && c <= 'Z';
    private static readonly Func<char, bool> IsDigit = c => c >= '0' && c <= '9';
    private static readonly Func<char, bool> IsNonAlphaNumeric = c => !(IsLower(c) || IsUpper(c) || IsDigit(c));

    public static implicit operator string(PasswordValueObject passwordValueObject) =>
        passwordValueObject?.Password ?? string.Empty;

    [SugarColumn(ColumnName = "salt")]
    public string Salt { get; set; }

    // public string HashCode
    // {
    //     get { return (Salt + Value).Sha256(); }
    // }
    [SugarColumn(ColumnName = "password")]
    public string Password { get; set; }

    public PasswordValueObject()
    {
    }

    public PasswordValueObject(string value)
    {
        Salt = HashCrypto.BuildSalt();
        if (string.IsNullOrWhiteSpace(value) || MinPasswordLength > value.Length)
            throw new LogicErrorException("密码不能为空，最小设定6位数密码。");
        Password = HashCrypto.GeneratePwd(value, Salt);
    }


    protected override IEnumerable<object> GetEqualityComponents()
    {
        yield return Password;
        yield return Salt;
    }
}